package com.atguigu.gulimall.auth.controller;

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.vo.UserRegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@Controller
public class RegisterController {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private MemberFeignService memberFeignService;

    private final String HOST = "http://auth.gulimall.com";

    /**
     * 重定向携带数据，是利用session的原理，只要跳到下一个页面，session里面的数据就会删除
     *
     * @param userRegisterVo
     * @param result
     * @param redirectAttributes 模拟重定向携带数据
     * @return
     */
    @PostMapping("/register")
    public String register(@Valid UserRegisterVo userRegisterVo,
                           BindingResult result,
                           RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {
            Map<String, String> errors = new HashMap<>();
            for (FieldError fieldError : result.getFieldErrors()) {
                errors.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            redirectAttributes.addFlashAttribute("errors", errors);
            // 校验出错，转发到注册页 (注意：forward会报post不支持 错误)
            // 因为/reg.html路径映射 是get方式，而当前方法是post
//            return "forward:/reg.html";
            return "redirect:" + HOST + "/reg.html";
        }
        // 校验验证码
        String code = userRegisterVo.getCode();
        String key = AuthServerConstant.SMS_CODE_CACHE_PREFIX + userRegisterVo.getPhone();
        String redisCode = redisTemplate.opsForValue().get(key);
        if (!StringUtils.isEmpty(redisCode) && code.equals(redisCode.split("_")[0])) {
            // 删除验证码；令牌机制
            redisTemplate.delete(key);
            // 验证码通过， 真正的注册
            R r = memberFeignService.register(userRegisterVo);
            if (r.getCode() == 0) {
                // 注册成功，重定向到登录页
                return "redirect:" + HOST + "/login.html";
            } else {
                // 失败
                redirectAttributes.addFlashAttribute(
                        "errors",
                        MapUtil.builder()
                                .put("msg", r.getData(new TypeReference<String>() {}))
                                .map()
                );
                return "redirect:" + HOST + "/reg.html";
            }
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:" + HOST + "/reg.html";
        }
    }
}
